package org.apache.ocean.main.client;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.apache.ocean.main.client.OceanXML.RequestException;
import org.apache.ocean.main.http.HttpParameters;
import org.apache.ocean.main.http.HttpTimeout;
import org.apache.ocean.main.http.MulticastHttp;
import org.apache.ocean.main.http.MulticastHttp.AllExceptions;
import org.apache.ocean.main.http.MulticastHttp.ExceptionEnum;
import org.apache.ocean.main.replication.Replication.ReplicationException;

public class LargeBatchClient {
	private List<URL> urls;
	private URL url;
	private String category;
	private Long indexID;
	private ExecutorService threadPool;
	private HttpTimeout httpTimeout;
	
	public LargeBatchClient(Long indexID, URL url, List<URL> urls, String category, HttpTimeout httpTimeout, ExecutorService threadPool) {
		this.url = url;
		this.urls = urls;
		this.category = category;
		this.indexID = indexID;
		this.httpTimeout = httpTimeout;
		this.threadPool = threadPool;
	}
	
	public void commit() throws Exception {
		try {
			syncIndex();
		} catch (Exception exception) {
			try {
				rollback();
			} catch (Exception rollbackException) {
				throw new ReplicationException("error rolling back syncIndex", rollbackException);
			}
			throw new Exception("error syncIndex", exception);
		}
		try {
			doCommit();
		} catch (Exception exception) {
			try {
				rollback();
			} catch (Exception rollbackException) {
				throw new Exception("error rolling back commit", rollbackException);
			}
			throw new Exception("error commit", exception);
		}
	}
  
	private void syncIndex() throws IOException, RequestException, InterruptedException, AllExceptions {
		execute("syncindex");
	}

	public void doCommit() throws IOException, RequestException, InterruptedException, AllExceptions {
		execute("commit");
	}

	public void rollback() throws IOException, RequestException, InterruptedException, AllExceptions {
		execute("rollback");
	}

	private void execute(String action) throws IOException, RequestException, InterruptedException, AllExceptions {
		MulticastHttp multicastHttp = new MulticastHttp(threadPool, ExceptionEnum.ALL);
		HttpParameters httpParameters = new HttpParameters();
		httpParameters.add("action", "largebatch");
		httpParameters.add("largebatchaction", action);
		httpParameters.add("category", category);
		httpParameters.add("indexid", indexID);
		httpParameters.add("url", url);
		List<OceanXML> responses = multicastHttp.execute(urls, httpParameters, httpTimeout);
	}
}
